package com.zhiche.lisa.tms.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.zhiche.lisa.core.enums.TableStatusEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.supports.RestfulResponse;
import com.zhiche.lisa.core.utils.Account.AccountUtil;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.core.utils.SnowFlakeId;
import com.zhiche.lisa.oms.dao.model.Order;
import com.zhiche.lisa.oms.dao.model.OrderContact;
import com.zhiche.lisa.oms.dao.model.OrderItem;
import com.zhiche.lisa.oms.dto.HuiyuncheShipInfoDTO;
import com.zhiche.lisa.oms.dto.OrdercostDTO;
import com.zhiche.lisa.oms.dto.ShipmentOrderDTO;
import com.zhiche.lisa.oms.enums.CodePrefixEnum;
import com.zhiche.lisa.oms.enums.FailureDataType;
import com.zhiche.lisa.oms.service.InterfaceCompensationService;
import com.zhiche.lisa.oms.vo.LocationVo;
import com.zhiche.lisa.tms.dao.mapper.ShipOrderMapper;
import com.zhiche.lisa.tms.dao.model.*;
import com.zhiche.lisa.tms.dao.model.bo.GenerateOrderBO;
import com.zhiche.lisa.tms.dao.model.bo.GenerateShipOrderBO;
import com.zhiche.lisa.tms.dao.model.bo.ShipLineInfoBO;
import com.zhiche.lisa.tms.dto.*;
import com.zhiche.lisa.tms.service.*;
import com.zhiche.lisa.tms.vo.CarrierInfoLineVO;
import com.zhiche.lisa.tms.vo.ServiceTypeVO;
import com.zhiche.lisa.util.MdmUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 运单 服务实现类
 * </p>
 *
 * @author qichao
 * @since 2018-06-18
 */
@Service
public class ShipOrderServiceImpl extends ServiceImpl<ShipOrderMapper, ShipOrder> implements IShipOrderService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ShipOrderServiceImpl.class);

    @Autowired
    private IShipOrderService shipOrderService;

    @Autowired
    private IShipOrderItemService shipOrderItemService;

    @Autowired
    private IShipTaskService shipTaskService;

    @Autowired
    private IShipmentService shipmentService;

    @Autowired
    private IShipmentDetailService shipmentDetailService;

    @Autowired
    private IShipTaskLocationService shipTaskLocationService;

    @Autowired
    private IShipTaskContactService shipTaskContactService;

    @Autowired
    private MdmUtil mdmUtil;

    @Autowired
    private TmsExplogLineService explogLineService;

    @Autowired
    private InterfaceCompensationService interfaceCompensationService;

    @Value("${lisa.lspm.getCarrierInfoByPlate}")
    private String getCarrierInfoByPlate;
    @Value("${lisa.bms.importPurchaseUrl}")
    private String importPurchaseUrl;
    @Value("${lisa.bms.importPurchaseAndDtl}")
    private String importPurchaseAndDtl;
    @Value("${lisa.bms.updateOrInsertPurchaseUrl}")
    private String updateOrInsertPurchaseUrl;
    @Value("${lisa.bms.deletePurchaseUrl}")
    private String deletePurchaseUrl;
    //连接超时时间
    @Value("${lisa.socketTimeout}")
    private int socketTimeout;
    @Value("${integration.getPriceAndMilesUrl}")
    private String getPriceAndMilesUrl;
    @Value("${integration.url}")
    private String integrationUrl;
    @Value("${lisa.lspm.getDriverInfoById}")
    private String getDriverInfoById;
    @Value("${lisa.lspm.queryFleetBasic}")
    private String queryFleetBasic;


    @Autowired
    private SnowFlakeId snowFlakeId;

    @Override
    public ShipOrder getShipOrderByTaskCode(String shipTaskCode) {
        ShipOrder shipOrder = null;
        ShipOrder shipOrderList = shipOrderService.getShipOrderByTaskCode(shipTaskCode);
//        if (!CollectionUtils.isEmpty(shipOrderList)) {
//            shipOrder = shipOrderList.get(0);
//        }
        return shipOrder;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void generateShipOrder(GenerateShipOrderBO generateShipOrderBO, String authorization) {

        // 生成订单数
        List<GenerateOrderBO> generateOrderBOList = generateShipOrderBO.getGenerateOrderBOList();
        // 所有明细
        List<ShipLineInfoBO> allDetailList = generateShipOrderBO.getShipLineInfoBOList();
        if (CollectionUtils.isEmpty(generateOrderBOList)
                || CollectionUtils.isEmpty(allDetailList))
            return;

        // 查询牵引车信息
        CarrierInfoLineVO carrierInfoLineVO = selectCarrierInfoByPlate(generateShipOrderBO.getVclicense(), authorization);
        LOGGER.info("ShipOrderServierImpl.autoShipment carrierInfoLineVO:{} ", JSON.toJSONString(carrierInfoLineVO));
        if (carrierInfoLineVO == null)
            throw new BaseException("车牌号无法找到对应的牵引车信息");

        // 生成装车单
        Shipment shipment = new Shipment();
        // 装车单编号
        String shipCode = "SP" + snowFlakeId.nextId();
        shipment.setCode(shipCode);

        // 承运商/人标识
        if (carrierInfoLineVO != null) {
            if (carrierInfoLineVO.getLspId() != null) {
                shipment.setCarrierId(String.valueOf(carrierInfoLineVO.getLspId()));
            } else {
                if (carrierInfoLineVO.getDriverId() != null) {
                    shipment.setCarrierId(String.valueOf(carrierInfoLineVO.getDriverId()));
                }
            }
        }
        // 车牌号
        shipment.setTransportationId(generateShipOrderBO.getVclicense());
        // 具体司机标识
        if (carrierInfoLineVO != null) {
            shipment.setDriverId((carrierInfoLineVO.getDriverId() == null) ? "" : String.valueOf(carrierInfoLineVO.getDriverId()));
        }
        // 具体司机姓名
        if (carrierInfoLineVO != null) {
            shipment.setDriverName(carrierInfoLineVO.getDriverName());
        }
        // 具体司机电话
        if (carrierInfoLineVO != null) {
            shipment.setDriverPhone(carrierInfoLineVO.getDriverMobile());
        }
        // 实际交付时间
        shipment.setGmtDeliver(generateShipOrderBO.getDtarrive());
        // 创建时间
        shipment.setGmtCreate(new Date());
        // 插入装车单
        shipmentService.insert(shipment);

        Integer taskNum = 0;
        for (GenerateOrderBO generateOrderBO : generateOrderBOList) {

            ShipOrder shipOrder = new ShipOrder();
            // 运单编号
            String orderCode = "SO" + snowFlakeId.nextId();
            shipOrder.setCode(orderCode);

            // 创建时间
            shipOrder.setGmtCreate(new Date());
            // 生成运单
            this.insert(shipOrder);

            // 生成任务
            ShipTask shipTask = new ShipTask();
            // 任务编号
            String taskCode = "ST" + snowFlakeId.nextId();
            shipTask.setCode(taskCode);

            // 运单编号
            shipTask.setShipOrderCode(shipOrder.getCode());
            // 创建时间
            shipTask.setGmtCreate(new Date());
            // 承运商/人标识
            if (carrierInfoLineVO != null) {
                if (carrierInfoLineVO.getLspId() != null) {
                    shipTask.setCarrierId(String.valueOf(carrierInfoLineVO.getLspId()));
                } else {
                    if (carrierInfoLineVO.getDriverId() != null) {
                        shipTask.setCarrierId(String.valueOf(carrierInfoLineVO.getDriverId()));
                    }
                }
            }
            // 生成任务
            shipTaskService.insert(shipTask);

            ShipTaskLocation shipTaskLocation = new ShipTaskLocation();
            // 任务编号
            shipTaskLocation.setShipTaskCode(shipTask.getCode());
            // 起点对应的location code
            shipTaskLocation.setOriginLocationCode(String.valueOf(generateOrderBO.getShippingLocationId()));
            // 终点对应的location code
            shipTaskLocation.setDestLocationCode(String.valueOf(generateOrderBO.getDeliveryLocationId()));
            // 运输任务起止点信息
            shipTaskLocationService.insert(shipTaskLocation);

            // 生成装车单明细
            ShipmentDetail shipmentDetail = new ShipmentDetail();
            // 装车单 id
            shipmentDetail.setShipmentId(shipment.getId());
            // 任务编号
            shipmentDetail.setShipTaskCode(shipTask.getCode());
            // 运输任务开始顺序
            shipmentDetail.setShipTaskOriginOrder(taskNum);
            // 运输任务结束顺序
            shipmentDetail.setShipTaskDestOrder(taskNum);
            // 创建时间
            shipmentDetail.setGmtCreate(new Date());
            // 插入装车单明细
            shipmentDetailService.insert(shipmentDetail);

            for (ShipLineInfoBO shipLineInfoBO : allDetailList) {

                if (generateOrderBO.getIstartcityid().equals(shipLineInfoBO.getIstartcityid())
                        && generateOrderBO.getIendcityid().equals(shipLineInfoBO.getIendcityid())) {
                    ShipOrderItem shipOrderItem = new ShipOrderItem();
                    // 运单编号
                    shipOrderItem.setShipOrderCode(shipOrder.getCode());
                    // 订单货物编号
                    shipOrderItem.setOrderItemId(shipLineInfoBO.getOrderItemId());
                    // 创建时间
                    shipOrderItem.setGmtCreate(new Date());
                    // 保存运单货物明细
                    shipOrderItemService.insert(shipOrderItem);
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<OrderAssignDTO> autoShipment(ShipmentAutoDTO shipmentAutoDTO, String authorization) {

        CarrierInfoLineVO carrierInfoLineVO = selectCarrierInfoByPlate(shipmentAutoDTO.getTransportationId(),
                authorization);
        LOGGER.info("ShipOrderServierImpl.autoShipment carrierInfoLineVO:{} ", JSON.toJSONString(carrierInfoLineVO));
        // 承运商/人标识
        if (carrierInfoLineVO != null) {
            shipmentAutoDTO.setCarrierId(String.valueOf(carrierInfoLineVO.getLspId()));
        }
        // 具体司机标识
        if (carrierInfoLineVO != null) {
            shipmentAutoDTO.setDriverId((carrierInfoLineVO.getDriverId() == null) ? "" : String.valueOf(carrierInfoLineVO.getDriverId()));
        }
        // 具体司机姓名
        if (carrierInfoLineVO != null) {
            shipmentAutoDTO.setDriverName(carrierInfoLineVO.getDriverName());
        }
        // 具体司机电话
        if (carrierInfoLineVO != null) {
            shipmentAutoDTO.setDriverPhone(carrierInfoLineVO.getDriverMobile());
        }

        List<ShipTask> shipTaskList = Lists.newArrayList();

        List<OrderAssignDTO> orderAssignDTOList = Lists.newArrayList();
        List<OmsOrder> orderList = shipmentAutoDTO.getOrderList();
        if (CollectionUtils.isNotEmpty(orderList)) {
            for (OmsOrder order : orderList) { //每个订单生成一个运单

                ShipOrder shipOrder = new ShipOrder();
                shipOrder.setTenantId(shipmentAutoDTO.getTenantId());
                shipOrder.setCode("SO" + snowFlakeId.nextId());
                this.insert(shipOrder);

                for (OmsOrderItem omsOrderItem : order.getOrderItemList()) { //按订单明细生成运单明细
                    ShipOrderItem shipOrderItem = new ShipOrderItem();
                    shipOrderItem.setShipOrderCode(shipOrder.getCode());
                    shipOrderItem.setOrderItemId(omsOrderItem.getId());
                    shipOrderItem.setTenantId(shipmentAutoDTO.getTenantId());
                    shipOrderItem.setIssueItemId(omsOrderItem.getIssueItemId());
                    shipOrderItem.setMaterial(omsOrderItem.getMaterial());
                    shipOrderItemService.insert(shipOrderItem);

                    OrderAssignDTO orderAssignDTO = new OrderAssignDTO();
                    orderAssignDTO.setOrderCode(order.getCode());
                    orderAssignDTO.setOrderItemCode(omsOrderItem.getId());
                    orderAssignDTO.setConsignCode(shipOrder.getCode());
                    orderAssignDTO.setGmtConsign(shipOrder.getGmtCreate());
                    orderAssignDTOList.add(orderAssignDTO);
                }

                // 生成任务
                ShipTask shipTask = new ShipTask();
                // 任务编号
                shipTask.setCode("ST" + snowFlakeId.nextId());
                // 运单编号
                shipTask.setShipOrderCode(shipOrder.getCode());
                shipTask.setCarrierId(shipmentAutoDTO.getCarrierId());
                shipTask.setTenantId(Integer.valueOf(shipmentAutoDTO.getTenantId().toString()));
                shipTaskService.insert(shipTask);
//            shipTask.setGmtExpectStart(shipmentAutoDTO.);
//            shipTask.setGmtExpectFinish();


                ShipTaskLocation shipTaskLocation = new ShipTaskLocation();
                // 任务编号
                shipTaskLocation.setShipTaskCode(shipTask.getCode());
                // 起点对应的location code
                shipTaskLocation.setOriginLocationCode(order.getOrderLocation().getShippingLocationId().toString());
                // 终点对应的location code
                shipTaskLocation.setDestLocationCode(order.getOrderLocation().getDeliveryLocationId().toString());
                shipTaskLocation.setTenantId(shipmentAutoDTO.getTenantId());
                shipTaskLocationService.insert(shipTaskLocation);

                shipTaskList.add(shipTask);
            }

            // 生成装车单
            Shipment shipment = new Shipment();
            // 装车单编号
            String shipCode = "SP" + snowFlakeId.nextId();
            BeanUtils.copyProperties(shipmentAutoDTO, shipment);
            shipment.setCode(shipCode);
            shipment.setTenantId(shipmentAutoDTO.getTenantId());
            // 插入装车单
            shipment.setShipSourceKey(orderList.get(0).getCustomerOrderId());
            shipmentService.insert(shipment);

            int taskNum = 0;
            for (ShipTask shipTask : shipTaskList) {
                taskNum++;
                // 生成装车单明细
                ShipmentDetail shipmentDetail = new ShipmentDetail();
                // 装车单 id
                shipmentDetail.setShipmentId(shipment.getId());
                // 任务编号
                shipmentDetail.setShipTaskCode(shipTask.getCode());
                // 运输任务开始顺序
                shipmentDetail.setShipTaskOriginOrder(taskNum);
                // 运输任务结束顺序
                shipmentDetail.setShipTaskDestOrder(taskNum);
                shipmentDetail.setTenantId(shipmentAutoDTO.getTenantId());
                shipmentDetailService.insert(shipmentDetail);
            }
        }
        return orderAssignDTOList;
    }

    @Override
    public ShipOrder getShipOrderByItemId(Long itemId) {

        if (itemId == null)
            return null;

        Wrapper<ShipOrder> shipOrderWrapper = new EntityWrapper<>();
        shipOrderWrapper.addFilter("code=(select ship_order_code from lisa_ship_order_item where order_item_id=" + itemId + ")");
        List<ShipOrder> shipOrderList = selectList(shipOrderWrapper);

        if (CollectionUtils.isEmpty(shipOrderList))
            return null;

        return shipOrderList.get(0);
    }

    private CarrierInfoLineVO selectCarrierInfoByPlate(String plate, String authorization) {
        CarrierInfoLineVO carrierInfoLineVO = null;
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
        List<NameValuePair> params = Lists.newArrayList();
        params.add(new BasicNameValuePair("plate", plate));
        String strReturn = HttpClientUtil.get(getCarrierInfoByPlate, headNamePairs, params, socketTimeout);
        if (!StringUtils.isEmpty(strReturn)) {
            RestfulResponse<CarrierInfoLineVO> restfulResponse = JSON.parseObject(strReturn, new TypeReference<RestfulResponse<CarrierInfoLineVO>>() {
            });
            carrierInfoLineVO = restfulResponse.getData();
        }
        return carrierInfoLineVO;
    }

    private CarrierInfoLineVO queryFleetBasicWithId(String fleetId, String token) {
        CarrierInfoLineVO carrierInfoLineVO = null;
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", token));
        Map<String, String> params = new LinkedHashMap<>();
        params.put("fleetId", fleetId);
        String jsonParam = JSONObject.toJSONString(params);
        LOGGER.info("tms-->lspm 获取车队信息 url:{},param:{}", queryFleetBasic, jsonParam);
        String strReturn = null;
        try {
            strReturn = HttpClientUtil.postJson(queryFleetBasic, headNamePairs, jsonParam, socketTimeout);
            LOGGER.info("tms-->lspm 获取车队信息 param:{},result:{}", jsonParam, strReturn);
            if (org.apache.commons.lang3.StringUtils.isNotBlank(strReturn)) {
                carrierInfoLineVO = new CarrierInfoLineVO();
                JSONObject ro = JSONObject.parseObject(strReturn);
                //返回成功
                if (org.apache.commons.lang3.StringUtils.isNotBlank(ro.getString("code"))
                        && TableStatusEnum.STATUS_0.getCode().equals(ro.getString("code"))) {
                    String data = ro.getString("data");
                    JSONObject dataOb = JSONObject.parseObject(data);
                    if (dataOb != null) {
                        carrierInfoLineVO.setLspId(Long.valueOf(dataOb.getString("lspId")));
                        carrierInfoLineVO.setLspName(dataOb.getString("lspName"));
                        carrierInfoLineVO.setFleetId(Long.valueOf(fleetId));
                        carrierInfoLineVO.setFleetName(dataOb.getString("fleetName"));
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.info("tms-->lspm 获取车队信息 失败: url:{},param:{},error:{}", getCarrierInfoByPlate, jsonParam, e);
        }
        return carrierInfoLineVO;
    }

    /**
     * 根据oms的传过来的数据生成装车单和运单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<OrderAssignDTO> addShipment(ShipmentOrderDTO shipmentOrderDTO, String authorization) {
        LOGGER.info("ShipmentOrderDTO:{}",JSON.toJSONString(shipmentOrderDTO));
        List<OrderAssignDTO> orderAssignDTOList = Lists.newArrayList();
        CarrierInfoLineVO carrierInfoLineVO = null;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(shipmentOrderDTO.getPlateNo())) {
            //正常牵引车下发指令
            carrierInfoLineVO = selectCarrierInfoByPlate(shipmentOrderDTO.getPlateNo(), authorization);
        }
        if (carrierInfoLineVO == null
                && org.apache.commons.lang3.StringUtils.isNotBlank(shipmentOrderDTO.getServiceProviderId())) {
            //针对魏军车队做为供方,司机/车牌接收指令  便于B->C结算
            carrierInfoLineVO = queryFleetBasicWithId(shipmentOrderDTO.getFleetId(), authorization);
        }
        if (carrierInfoLineVO != null
                && shipmentOrderDTO.getTransactionCode().equals("IU")) {
            Long tenantId = shipmentOrderDTO.getTenantId();
            Shipment shipment = null;
            // 修改添加明细 不生成装车单(一个指令一个装车单)
            if (!TableStatusEnum.STATUS_1.getCode().equals(shipmentOrderDTO.getIsUpdate())) {
                shipment = new Shipment();
                // 装车单编号
                shipment.setCode("SP" + snowFlakeId.nextId());
                shipment.setTenantId(tenantId);
                shipment.setTransTypeId(StringUtils.isEmpty(shipmentOrderDTO.getTransportModeId()) ? 0L : Long.valueOf(shipmentOrderDTO.getTransportModeId()));
                shipment.setLspId(carrierInfoLineVO.getLspId().toString());
                shipment.setLspName(carrierInfoLineVO.getLspName());
                if (!StringUtils.isEmpty(carrierInfoLineVO.getFleetId())) {
                    shipment.setFleetId(carrierInfoLineVO.getFleetId().toString());
                    shipment.setFleetName(carrierInfoLineVO.getFleetName());
                }
                if (Objects.nonNull(carrierInfoLineVO.getId()))
                    shipment.setCarrierId(carrierInfoLineVO.getId().toString());
                shipment.setTransportationId(shipmentOrderDTO.getPlateNo());
                shipment.setDriverId(shipmentOrderDTO.getDriverId());
                shipment.setShipSourceKey(shipmentOrderDTO.getShipmentId());
                List<NameValuePair> headNamePairs = Lists.newArrayList();
                headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
                if (!StringUtils.isEmpty(shipmentOrderDTO.getDriverId())) {
                    String result = HttpClientUtil.get(getDriverInfoById + "/" + shipmentOrderDTO.getDriverId() + "/" + 0, headNamePairs, null, socketTimeout);
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    if (jsonObject.getInteger("code") == 0) {
                        shipment.setDriverName(jsonObject.getJSONObject("data").getString("name"));
                        shipment.setDriverPhone(jsonObject.getJSONObject("data").getString("mobile"));
                    }
                }
                //
                EntityWrapper<Shipment> shipmentWrapper=new EntityWrapper<>();
                shipmentWrapper.eq("ship_source_key",shipmentOrderDTO.getShipmentId()).eq("is_delete", TableStatusEnum.STATUS_1.getCode()).isNotNull("wms_ship_time");
                List<Shipment> shipments = shipmentService.selectListNotenant(shipmentWrapper);
                if (CollectionUtils.isNotEmpty(shipments)){
                    shipment.setWmsShipTime(shipments.get(0).getWmsShipTime());
                    shipment.setGmtCreate(shipments.get(0).getGmtCreate());
                }
                // 插入装车单
                shipmentService.insert(shipment);
            } else {
                EntityWrapper<ShipTask> ew = new EntityWrapper<>();
                ew.eq("ship_order_code", shipmentOrderDTO.getShipOrderCode())
                        .orderBy("id", false);
                ShipTask task = shipTaskService.selectOne(ew);
                if (task != null) {
                    EntityWrapper<ShipmentDetail> detailEW = new EntityWrapper<>();
                    detailEW.eq("ship_task_code", task.getCode())
                            .orderBy("id", false);
                    ShipmentDetail detail = shipmentDetailService.selectOne(detailEW);
                    if (detail != null) {
                        shipment = shipmentService.selectById(detail.getShipmentId());
                    }
                }
            }

            if (shipment != null) {
                for (Order order : shipmentOrderDTO.getOrderList()) { //每个订单生成一个运单
                    LOGGER.info("运单:{}",JSON.toJSONString(order));
                    //运单
                    ShipOrder shipOrder = new ShipOrder();
                    shipOrder.setTenantId(tenantId);
                    shipOrder.setCode("SO" + snowFlakeId.nextId());
                    this.insert(shipOrder);

                    // 生成任务
                    ShipTask shipTask = new ShipTask();
                    // 任务编号
                    shipTask.setCode("ST" + snowFlakeId.nextId());
                    // 运单编号
                    shipTask.setShipOrderCode(shipOrder.getCode());

                    shipTask.setCarrierId(StringUtils.isEmpty(carrierInfoLineVO.getId()) ?
                            null : carrierInfoLineVO.getId().toString());
                    shipTask.setTenantId(Integer.valueOf(tenantId.toString()));
                    shipTask.setTransTypeId(StringUtils.isEmpty(shipmentOrderDTO.getTransportModeId()) ? 0L : Long.valueOf(shipmentOrderDTO.getTransportModeId()));
                    shipTaskService.insert(shipTask);

                    for (OrderItem omsOrderItem : order.getOrderItemList()) { //按订单明细生成运单明细
                        LOGGER.info("运单明细:{}",JSON.toJSONString(omsOrderItem));
                        EntityWrapper<ShipOrderItem> shipOrderItemWrapper=new EntityWrapper<>();
                        shipOrderItemWrapper.eq("g.item_source_key",omsOrderItem.getItemSourceKey()).eq("a.ship_source_key",shipmentOrderDTO.getShipmentId()).eq("g.is_delete",1).isNotNull("g.wms_ship_time");
                       // List<ShipOrderItem> shipOrderItems = shipOrderItemService.selectListNotenant(shipOrderItemWrapper);
                        List<ShipOrderItem> shipOrderItems = shipOrderItemService.getListNotenant(shipOrderItemWrapper);
                        ShipOrderItem shipOrderItem = new ShipOrderItem();
                        if (CollectionUtils.isNotEmpty(shipOrderItems)) {
                           shipOrderItem.setWmsShipTime(shipOrderItems.get(0).getWmsShipTime());
                        }
                        shipOrderItem.setShipOrderCode(shipOrder.getCode());
                        shipOrderItem.setOrderItemId(omsOrderItem.getId());
                        shipOrderItem.setTenantId(tenantId);
                        shipOrderItem.setCiamsId(omsOrderItem.getCiamsId());
                        LOGGER.info("末端指令标识:{}",omsOrderItem.getIsTerminal());
                        if (!org.apache.commons.lang3.StringUtils.isEmpty(omsOrderItem.getIsTerminal())){
                            shipOrderItem.setTerminal(omsOrderItem.getIsTerminal());
                            ShipOrderItem shipOrderItem1=shipOrderItemService.getShipOrderItemByOrderNo(omsOrderItem.getOrderNo(),omsOrderItem.getItemSourceKey());
                            if ("1".equals(omsOrderItem.getIsTerminal())){
                                if (shipOrderItem1==null){
                                    shipOrderItem.setReceiptStatus("待回单");
                                }else{
                                    if ("".equals(shipOrderItem1.getReceiptStatus()) && shipOrderItem1.getReceiptStatus()==null){
                                        shipOrderItem.setReceiptStatus("待回单");
                                    }else {
                                        shipOrderItem.setReceiptStatus(shipOrderItem1.getReceiptStatus());
                                    }
                                }
                            }
                        }
                        shipOrderItem.setCusWaybillId(omsOrderItem.getCusWaybillId());
                        shipOrderItem.setIssueItemId(omsOrderItem.getIssueItemId());
                        shipOrderItem.setMaterial(omsOrderItem.getMaterial());
                        shipOrderItem.setItemSourceKey(omsOrderItem.getItemSourceKey());
                        shipOrderItem.setOrderDate(omsOrderItem.getOrderDate());
                        shipOrderItem.setOrderNo(omsOrderItem.getOrderNo());
                        shipOrderItemService.insert(shipOrderItem);

                        OrderAssignDTO orderAssignDTO = new OrderAssignDTO();
                        orderAssignDTO.setOrderCode(order.getCode());
                        orderAssignDTO.setOrderItemCode(omsOrderItem.getId());
                        orderAssignDTO.setConsignCode(shipOrder.getCode());
                        orderAssignDTO.setGmtConsign(shipOrder.getGmtCreate());
                        orderAssignDTOList.add(orderAssignDTO);
                        //insertPricePurchaseIU(shipmentOrderDTO, shipment.getCode(), shipTask.getCode(), shipOrderItem, carrierInfoLineVO, order.getLocation(), authorization);
                    }

                    //运输任务联系人
                    OrderContact omsOrderContact = order.getOrderContact();
                    ShipTaskContact shipTaskContact = new ShipTaskContact();
                    shipTaskContact.setDestContactName(omsOrderContact.getContactsName());
                    shipTaskContact.setDestContactPhone(omsOrderContact.getContactsPhone());
                    shipTaskContact.setOriginContactName(omsOrderContact.getContactsName());
                    shipTaskContact.setOriginContactPhone(omsOrderContact.getContactsPhone());
                    shipTaskContact.setShipTaskCode(shipTask.getCode());
                    shipTaskContact.setTenantId(tenantId);
                    shipTaskContactService.insert(shipTaskContact);

                    ShipTaskLocation shipTaskLocation = new ShipTaskLocation();
                    // 任务编号
                    shipTaskLocation.setShipTaskCode(shipTask.getCode());
                    // 起点对应的location code
                    shipTaskLocation.setOriginLocationCode(order.getOrderLocation().getShippingLocationId().toString());
                    // 终点对应的location code
                    shipTaskLocation.setDestLocationCode(order.getOrderLocation().getDeliveryLocationId().toString());
                    shipTaskLocation.setTenantId(tenantId);
                    shipTaskLocationService.insert(shipTaskLocation);

                    // 生成装车单跟运单关系
                    ShipmentDetail shipmentDetail = new ShipmentDetail();
                    // 装车单 id
                    shipmentDetail.setShipmentId(shipment.getId());
                    // 任务编号
                    shipmentDetail.setShipTaskCode(shipTask.getCode());
                    // 运输任务开始顺序
                    shipmentDetail.setShipTaskOriginOrder(Integer.valueOf(order.getOriginLocationSequence()));
                    // 运输任务结束顺序
                    shipmentDetail.setShipTaskDestOrder(Integer.valueOf(order.getDestLocationSequence()));
                    shipmentDetail.setTenantId(tenantId);
                    shipmentDetailService.insert(shipmentDetail);

                }
            }
        } else if (shipmentOrderDTO.getTransactionCode().equals("R")) {
            for (Order omsOrder : shipmentOrderDTO.getOrderList()) {
                for (OrderItem omsOrderItem : omsOrder.getOrderItemList()) {
                    Wrapper<ShipOrderItem> shipOrderItemWrapper = new EntityWrapper<>();
                    shipOrderItemWrapper.eq("order_item_id", omsOrderItem.getId())
                            .eq("is_delete", 0)
                            .orderBy("id", false);
                    ShipOrderItem oldItem = shipOrderItemService.selectOne(shipOrderItemWrapper);
                    if (oldItem == null) {
                        // 新增
                        Wrapper<ShipOrderItem> shipOrderItemEntityWrapper = new EntityWrapper<>();
                        shipOrderItemEntityWrapper.eq("item_source_key", omsOrderItem.getItemSourceKey());
                        ShipOrderItem isExitShipOrderItem = shipOrderItemService.selectOne(shipOrderItemEntityWrapper);
                        if (Objects.isNull(isExitShipOrderItem)) {
                            ShipOrderItem newShipOrderItem = new ShipOrderItem();
                            newShipOrderItem.setShipOrderCode(shipmentOrderDTO.getShipOrderCode());
                            newShipOrderItem.setOrderItemId(omsOrderItem.getId());
                            newShipOrderItem.setTenantId(Long.valueOf(AccountUtil.getAccountInfoFromSecurityContext().getTenantId()));
                            newShipOrderItem.setIssueItemId(omsOrderItem.getIssueItemId());
                            newShipOrderItem.setMaterial(omsOrderItem.getMaterial());
                            newShipOrderItem.setItemSourceKey(omsOrderItem.getItemSourceKey());
                            shipOrderItemService.insert(newShipOrderItem);
                            Wrapper<ShipTask> shipTaskWrapper = new EntityWrapper<>();
                            shipTaskWrapper.eq("ship_order_code", shipmentOrderDTO.getShipOrderCode());
                            ShipTask shipTask = shipTaskService.selectOne(shipTaskWrapper);
                            Wrapper<ShipmentDetail> shipmentDetailWrapper = new EntityWrapper<>();
                            shipmentDetailWrapper.eq("ship_task_code", shipTask.getCode());
                            ShipmentDetail shipmentDetail = shipmentDetailService.selectOne(shipmentDetailWrapper);
                            Wrapper<Shipment> shipmentWrapper = new EntityWrapper<>();
                            shipmentWrapper.eq("id", shipmentDetail.getShipmentId());
                            Shipment shipment = shipmentService.selectOne(shipmentWrapper);
                            //updateInsertPurchase(shipmentOrderDTO,authorization,carrierInfoLineVO,omsOrderItem,newShipOrderItem,shipTask,shipment);
                        }
                    } else {
                        Wrapper<ShipOrder> shipOrderWrapper = new EntityWrapper<>();
                        shipOrderWrapper.eq("code", oldItem.getShipOrderCode());
                        ShipOrder shipOrder = shipOrderService.selectOne(shipOrderWrapper);
                        Wrapper<ShipTask> shipTaskWrapper = new EntityWrapper<>();
                        shipTaskWrapper.eq("ship_order_code", shipOrder.getCode());
                        ShipTask shipTask = shipTaskService.selectOne(shipTaskWrapper);
                        Wrapper<ShipmentDetail> shipmentDetailWrapper = new EntityWrapper<>();
                        shipmentDetailWrapper.eq("ship_task_code", shipTask.getCode());
                        ShipmentDetail shipmentDetail = shipmentDetailService.selectOne(shipmentDetailWrapper);
                        Wrapper<Shipment> shipmentWrapper = new EntityWrapper<>();
                        shipmentWrapper.eq("id", shipmentDetail.getShipmentId());
                        Shipment shipment = shipmentService.selectOne(shipmentWrapper);
                        // 删除
                        oldItem.setIsDelete(1);
                        shipOrderItemService.updateById(oldItem);
                        //deletePricePurchase(shipmentOrderDTO, authorization, shipTask, shipment, oldItem);
                    }
                }
                //判断整体订单运单 是否应该存在
                EntityWrapper<ShipOrderItem> ew = new EntityWrapper<>();
                ew.eq("ship_order_code", shipmentOrderDTO.getShipOrderCode())
                        .eq("is_delete", 0);
                List<ShipOrderItem> newShipOrderItems = shipOrderItemService.selectList(ew);
                if (CollectionUtils.isEmpty(newShipOrderItems)) {
                    deleteShipment(shipmentOrderDTO.getShipOrderCode(), shipmentOrderDTO, authorization);
                }
            }

        } else {
            deleteShipment(shipmentOrderDTO.getShipOrderCode(), shipmentOrderDTO, authorization);
        }
        return orderAssignDTOList;
    }

    /**
     * 人送指令新增
     */
    @Override
    public List<OrderAssignDTO> addHuiyuncheShipment(HuiyuncheShipInfoDTO infoDTO,
                                                     String auth,
                                                     Map<String, BigDecimal> otmRes) {
        Long tenantId = infoDTO.getTenantId();
        OrderItem item = infoDTO.getOrder().getOrderItemList().get(0);
        // 重复校验
        Shipment shipment = new Shipment();
        shipment.setShipSourceKey(infoDTO.getVcorderno());
        shipment.setTransTypeId(Long.valueOf(CodePrefixEnum.PEOPLESEND.getFix()));
        shipment.setIsDelete(0);
        shipment.setCode("SP" + snowFlakeId.nextId());
        //shipment.setCarrierId("");
        //shipment.setTransportationId("");
        shipment.setDriverId(infoDTO.getDriverId());
        shipment.setDriverName(infoDTO.getDriverName());
        shipment.setDriverPhone(infoDTO.getDriverPhone());
        shipment.setGmtCreate(new Date());
        //shipment.setGmtSetoff(new Date());
        //shipment.setGmtDeliver(new Date());
        shipment.setTenantId(infoDTO.getTenantId());
        shipment.setLspId(infoDTO.getLspId());
        shipment.setLspName(infoDTO.getLspName());
        shipment.setFleetId(infoDTO.getFleetId());
        shipment.setFleetName(infoDTO.getFleetName());
        shipmentService.insert(shipment);
        //运单
        ShipOrder shipOrder = new ShipOrder();
        shipOrder.setIsDelete(0);
        shipOrder.setCode("SO" + snowFlakeId.nextId());
        shipOrder.setGmtCreate(new Date());
        shipOrder.setTenantId(infoDTO.getTenantId());
        shipOrderService.insert(shipOrder);
        // 生成任务
        ShipTask shipTask = new ShipTask();
        shipTask.setTransTypeId(Long.valueOf(CodePrefixEnum.PEOPLESEND.getFix()));
        shipTask.setIsDelete(0);
        shipTask.setCode("ST" + snowFlakeId.nextId());
        shipTask.setShipOrderCode(shipOrder.getCode());
        shipTask.setIssuer(infoDTO.getVcvin());
        shipTask.setCarrierId("");
        shipTask.setGmtCreate(new Date());
        //shipTask.setGmtExpectStart(new Date());
        //shipTask.setGmtExpectFinish(new Date());
        shipTask.setTenantId(Integer.valueOf(infoDTO.getTenantId().toString()));
        //shipTask.setGmtStart(new Date());
        //shipTask.setGmtFinish(new Date());
        shipTask.setCreator("auto");
        //shipTask.setStartCreator("");
        //shipTask.setFinishCreator("");
        shipTaskService.insert(shipTask);
        //shiporderitem
        ShipOrderItem shipOrderItem = new ShipOrderItem();
        shipOrderItem.setIsDelete(0);
        shipOrderItem.setShipOrderCode(shipOrder.getCode());
        shipOrderItem.setOrderItemId(item.getId());
        shipOrderItem.setGmtCreate(new Date());
        shipOrderItem.setTenantId(infoDTO.getTenantId());
        shipOrderItem.setIssueItemId(infoDTO.getVcvin());
        shipOrderItem.setMaterial(infoDTO.getVcsstylename());
        shipOrderItem.setItemSourceKey(infoDTO.getVclineid());
        shipOrderItemService.insert(shipOrderItem);
        //运输任务联系人
        ShipTaskContact taskContact = new ShipTaskContact();
        taskContact.setIsDelete(0);
        taskContact.setShipTaskCode(shipTask.getCode());
        taskContact.setOriginContactName(infoDTO.getDriverName());
        taskContact.setOriginContactPhone(infoDTO.getDriverPhone());
        taskContact.setDestContactName(infoDTO.getDriverName());
        taskContact.setDestContactPhone(infoDTO.getDriverPhone());
        taskContact.setTenantId(infoDTO.getTenantId());
        shipTaskContactService.insert(taskContact);
        //shiptasklocation
        ShipTaskLocation taskLocation = new ShipTaskLocation();
        taskLocation.setIsDelete(0);
        taskLocation.setShipTaskCode(shipTask.getCode());
        taskLocation.setOriginLocationCode(infoDTO.getOrder().getOrderLocation().getDeliveryLocationId().toString());
        taskLocation.setDestLocationCode(infoDTO.getOrder().getOrderLocation().getShippingLocationId().toString());
        taskLocation.setTenantId(infoDTO.getTenantId());
        shipTaskLocationService.insert(taskLocation);
        //ShipmentDetail
        ShipmentDetail shipmentDetail = new ShipmentDetail();
        shipmentDetail.setIsDelete(0);
        shipmentDetail.setShipTaskCode(shipTask.getCode());
        shipmentDetail.setShipmentId(shipment.getId());
        shipmentDetail.setShipTaskOriginOrder(infoDTO.getShipTaskOriginOrder());
        shipmentDetail.setShipTaskDestOrder(infoDTO.getShipTaskDestOrder());
        shipmentDetail.setGmtCreate(new Date());
        shipmentDetail.setTenantId(infoDTO.getTenantId());
        shipmentDetailService.insert(shipmentDetail);
        // assign
        ArrayList<OrderAssignDTO> result = Lists.newArrayList();
        OrderAssignDTO orderAssignDTO = new OrderAssignDTO();
        orderAssignDTO.setOrderCode(infoDTO.getOrder().getCode());
        orderAssignDTO.setOrderItemCode(item.getId());
        orderAssignDTO.setConsignCode(shipOrder.getCode());
        orderAssignDTO.setGmtConsign(shipOrder.getGmtCreate());
        result.add(orderAssignDTO);
        //bms 支付价格
        PricePurchaseDTO pricePurchaseDTO = new PricePurchaseDTO();
        OrdercostDTO hyCostDTO = infoDTO.getOrdercosts(); // 人送订单的价格明细

        pricePurchaseDTO.setShipmentCode(shipment.getCode());
        pricePurchaseDTO.setVehicleTypeCode(StringUtils.isEmpty(infoDTO.getVcstylename()) ? infoDTO.getVehicledesc() : infoDTO.getVcstylename());
        pricePurchaseDTO.setVehicleClassifyId(infoDTO.getIstyleid());
        pricePurchaseDTO.setShipTaskCode(shipTask.getCode());
        pricePurchaseDTO.setItemUid(infoDTO.getVcvin());
        pricePurchaseDTO.setShipOrderItemId(shipOrderItem.getId());
        pricePurchaseDTO.setLspId(Long.valueOf(infoDTO.getLspId()));
        pricePurchaseDTO.setLspName(infoDTO.getLspName());
        pricePurchaseDTO.setDriverId(Long.valueOf(infoDTO.getDriverId()));
        pricePurchaseDTO.setDriverName(infoDTO.getDriverName());
        pricePurchaseDTO.setTransTypeId(Long.valueOf(CodePrefixEnum.PEOPLESEND.getFix()));
        //pricePurchaseDTO.setCarrierId(carrierInfoLineVO.getId());
        //pricePurchaseDTO.setCarrierPlate(shipmentOrderDTO.getPlateNo());
        if (!StringUtils.isEmpty(infoDTO.getFleetId())) {
            pricePurchaseDTO.setFleetId(Long.valueOf(infoDTO.getFleetId()));
            pricePurchaseDTO.setFleetName(infoDTO.getFleetName());
        }
        pricePurchaseDTO.setDepartLocationAdCode(infoDTO.getStartLocation().getAdCode());
        pricePurchaseDTO.setStartProvince(infoDTO.getVcstartprovince());
        pricePurchaseDTO.setStartCity(infoDTO.getVcstartcity());
        pricePurchaseDTO.setDepartLocationId(infoDTO.getStartLocation().getId());
        pricePurchaseDTO.setDepartAdressName(infoDTO.getStartLocation().getLabel());
        pricePurchaseDTO.setDepartAddressName(infoDTO.getStartLocation().getLabel());

        pricePurchaseDTO.setDestLocationId(infoDTO.getEndLocation().getId());
        pricePurchaseDTO.setEndProvince(infoDTO.getVcprovincename());
        pricePurchaseDTO.setEndCity(infoDTO.getVccityname());
        pricePurchaseDTO.setEnable(true);
        pricePurchaseDTO.setDestAdderssName(infoDTO.getVcaddress());
        pricePurchaseDTO.setDestLocationAdCode(infoDTO.getEndLocation().getAdCode());
        //
//        pricePurchaseDTO.setExtPurchasePrice(otmRes.get("price"));
//        pricePurchaseDTO.setMileage(otmRes.get("price"));

        pricePurchaseDTO.setCreateFrom(TableStatusEnum.STATUS_20.getCode());//10-OTM，20-人送，30-其他
        //pricePurchaseDTO.setCreator(Long.valueOf(AccountUtil.getAccountInfoFromSecurityContext().getAccountId()));
        pricePurchaseDTO.setTenantId(tenantId);
        pricePurchaseDTO.setWaybillDtlId(infoDTO.getVclineid());
        pricePurchaseDTO.setCusWaybill(infoDTO.getCusorderno());
        //推送人送价格明细
        PurchaseDetailDTO detailDTO = new PurchaseDetailDTO();
        //detailDTO.setId();
        //detailDTO.setHeadId("");
        detailDTO.setFirstOilCapacity(hyCostDTO.getFirstOilCapacity());//第一桶油量
        detailDTO.setVccard(hyCostDTO.getVccard());//身份证
        detailDTO.setFirstOilTotal(hyCostDTO.getFirstOilTotal());//第一桶油费
        detailDTO.setCardOilTotal(hyCostDTO.getCardOilTotal());
        detailDTO.setKilometer(hyCostDTO.getKilometer());
        detailDTO.setCardOilCapacity(hyCostDTO.getCardOilCapacity());
        detailDTO.setOilCost(hyCostDTO.getOilCost());
        detailDTO.setVcorderno(hyCostDTO.getVcorderno());
        detailDTO.setOrderlineId(infoDTO.getVcorderno());
        detailDTO.setOilPrice(hyCostDTO.getOilPrice());
        detailDTO.setServiceWage(hyCostDTO.getServiceWage());
        detailDTO.setSumCost(hyCostDTO.getConfirmTotalCost());
        detailDTO.setCurrentOilPrice(hyCostDTO.getCurrentOilPrice());
        detailDTO.setCurrentEffectDate(hyCostDTO.getCurrentEffectDate());
        //detailDTO.setGmtCreate();
        pricePurchaseDTO.setPricePurchaseDtl(detailDTO);

        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", auth));
        String strReturn = null;
        try {
            LOGGER.info("人送-->连接BMS 生成支付单据url:{},param:{}", importPurchaseAndDtl, JSON.toJSONString(pricePurchaseDTO));
            strReturn = HttpClientUtil.postJson(importPurchaseAndDtl, headNamePairs,
                    JSON.toJSONString(pricePurchaseDTO), socketTimeout);
            LOGGER.info("人送-->连接BMS 生成支付单据 result: {}", strReturn);
            if (StringUtils.isEmpty(strReturn)) {
                throw new BaseException("人送-->连接BMS 生成支付单据未响应,请稍后再试");
            } else {
                JSONObject parseObject = JSONObject.parseObject(strReturn);
                int code = parseObject.getIntValue("code");
                if (code != 0) {
                    throw new BaseException("人送-->连接BMS失败" + parseObject.getString("message"));
                }
            }
        } catch (Exception e) {
            LOGGER.error("人送-->连接BMS 生成支付单据连接异常: {}", e);
            throw new BaseException("人送-->连接BMS 生成支付单据连接异常,请稍后再试");
        }
        return result;
    }

    private void updateInsertPurchase(ShipmentOrderDTO shipmentOrderDTO, String authorization, CarrierInfoLineVO carrierInfoLineVO,
                                      OrderItem omsOrderItem, ShipOrderItem newShipOrderItem, ShipTask shipTask, Shipment shipment) {
        //四大家 判断
        LOGGER.info("连接BMS 获取支付暂估价--->param:{}", JSON.toJSONString(shipmentOrderDTO));
        if (FourPeopleEnum.JST.getId().equals(shipmentOrderDTO.getServiceProviderId())
                || FourPeopleEnum.JX.getId().equals(shipmentOrderDTO.getServiceProviderId())
                || FourPeopleEnum.LYTD.getId().equals(shipmentOrderDTO.getServiceProviderId())
                || FourPeopleEnum.YJ.getId().equals(shipmentOrderDTO.getServiceProviderId())) {
            PricePurchaseDTO pricePurchaseDTO = new PricePurchaseDTO();
            pricePurchaseDTO.setShipmentCode(shipment.getCode());
            pricePurchaseDTO.setShipTaskCode(shipTask.getCode());
            pricePurchaseDTO.setItemUid(newShipOrderItem.getIssueItemId());
            pricePurchaseDTO.setShipOrderItemId(newShipOrderItem.getId());
            pricePurchaseDTO.setLspId(carrierInfoLineVO.getLspId());
            pricePurchaseDTO.setLspName(carrierInfoLineVO.getLspName());
            pricePurchaseDTO.setDriverId(carrierInfoLineVO.getDriverId());
            pricePurchaseDTO.setDriverName(carrierInfoLineVO.getDriverName());
            pricePurchaseDTO.setTransTypeId(StringUtils.isEmpty(shipmentOrderDTO.getTransportModeId()) ? 0L : Long.valueOf(shipmentOrderDTO.getTransportModeId()));
            if (Objects.nonNull(carrierInfoLineVO.getId()))
                pricePurchaseDTO.setCarrierId(carrierInfoLineVO.getId());
            pricePurchaseDTO.setCarrierPlate(shipmentOrderDTO.getPlateNo());
            if (!StringUtils.isEmpty(carrierInfoLineVO.getFleetId())) {
                pricePurchaseDTO.setFleetId(carrierInfoLineVO.getFleetId());
                pricePurchaseDTO.setFleetName(carrierInfoLineVO.getFleetName());
            }
            LocationVo startLocation = omsOrderItem.getStartLocation();
            if (startLocation != null) {
                pricePurchaseDTO.setDepartLocationAdCode(startLocation.getAdCode());
                pricePurchaseDTO.setDepartAdressName(startLocation.getValue());
                pricePurchaseDTO.setDepartLocationId(startLocation.getId());
            }
            LocationVo endLocation = omsOrderItem.getEndLocation();
            if (endLocation != null) {
                pricePurchaseDTO.setDestLocationId(endLocation.getId());
                pricePurchaseDTO.setDestAdderssName(endLocation.getValue());
                pricePurchaseDTO.setDestLocationAdCode(endLocation.getAdCode());
            }
            Map<String, BigDecimal> stringBigDecimalMap = priceAndMiles(newShipOrderItem.getItemSourceKey(), authorization);
            if (stringBigDecimalMap != null) {
                pricePurchaseDTO.setExtPurchasePrice(stringBigDecimalMap.get("price"));
                pricePurchaseDTO.setMileage(stringBigDecimalMap.get("miles"));
            }
            pricePurchaseDTO.setCreateFrom(TableStatusEnum.STATUS_10.getCode());//10-OTM，20-人送，30-其他
            pricePurchaseDTO.setCreator(Long.valueOf(AccountUtil.getAccountInfoFromSecurityContext().getAccountId()));
            pricePurchaseDTO.setTenantId(Long.valueOf(AccountUtil.getAccountInfoFromSecurityContext().getTenantId()));
            List<NameValuePair> headNamePairs = Lists.newArrayList();
            headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
            String strReturn = null;
            try {
                LOGGER.info("连接BMS 生成支付单据url:{},param:{}", importPurchaseUrl, JSON.toJSONString(pricePurchaseDTO));
                strReturn = HttpClientUtil.postJson(importPurchaseUrl, headNamePairs,
                        JSON.toJSONString(pricePurchaseDTO), socketTimeout);
                LOGGER.info("连接BMS 生成支付单据 result:{}", strReturn);
            } catch (Exception e) {
                LOGGER.error("insertPricePurchaseIU error: {}", e);
            }
        }
    }

    private void deleteShipment(String shipOrderCode, ShipmentOrderDTO shipmentOrderDTO, String authorization) {

        if (StringUtils.isEmpty(shipOrderCode)) throw new BaseException("运单编号不能为空");
        Wrapper<ShipOrder> shipOrderWrapper = new EntityWrapper<>();
        shipOrderWrapper.eq("code", shipOrderCode);
        ShipOrder shipOrder = new ShipOrder();
        shipOrder.setIsDelete(1);
        shipOrderService.update(shipOrder, shipOrderWrapper);

        EntityWrapper<ShipOrderItem> shipOrderItemWrapper = new EntityWrapper<>();
        shipOrderItemWrapper.eq("ship_order_code", shipOrderCode).orderBy("id", false);
        ShipOrderItem shipOrderItem = new ShipOrderItem();
        shipOrderItem.setIsDelete(1);
        shipOrderItemService.update(shipOrderItem, shipOrderItemWrapper);
        List<ShipOrderItem> items = shipOrderItemService.selectListNotenant(shipOrderItemWrapper);
        ShipOrderItem orderItem = null;
        if (CollectionUtils.isNotEmpty(items)) {
            orderItem = items.get(0);
        }

        Wrapper<ShipTask> shipTaskWrapper = new EntityWrapper<>();
        shipTaskWrapper.eq("ship_order_code", shipOrderCode);
        ShipTask shipTask = new ShipTask();
        shipTask.setIsDelete(1);
        ShipTask oldshipTask = shipTaskService.selectOne(shipTaskWrapper);
        shipTaskService.update(shipTask, shipTaskWrapper);

        Wrapper<ShipTaskContact> shipTaskContactWrapper = new EntityWrapper<>();
        shipTaskContactWrapper.eq("ship_task_code", oldshipTask.getCode());
        ShipTaskContact shipTaskContact = new ShipTaskContact();
        shipTaskContact.setIsDelete(1);
        shipTaskContactService.update(shipTaskContact, shipTaskContactWrapper);

        Wrapper<ShipTaskLocation> shipTaskLocationWrapper = new EntityWrapper<>();
        shipTaskLocationWrapper.eq("ship_task_code", oldshipTask.getCode());
        ShipTaskLocation shipTaskLocation = new ShipTaskLocation();
        shipTaskLocation.setIsDelete(1);
        shipTaskLocationService.update(shipTaskLocation, shipTaskLocationWrapper);

        Wrapper<ShipmentDetail> shipmentDetailWrapper = new EntityWrapper<>();
        shipmentDetailWrapper.eq("ship_task_code", oldshipTask.getCode());
        ShipmentDetail shipmentDetail = new ShipmentDetail();
        shipmentDetail.setIsDelete(1);
        ShipmentDetail oldDetail = shipmentDetailService.selectOne(shipmentDetailWrapper);
        shipmentDetailService.update(shipmentDetail, shipmentDetailWrapper);
        Wrapper<ShipmentDetail> shipmentDetailEntityWrapper = new EntityWrapper<>();
        shipmentDetailEntityWrapper.eq("shipment_id", oldDetail.getShipmentId());
        List<ShipmentDetail> shipmentDetailList = shipmentDetailService.selectList(shipmentDetailEntityWrapper);
        int isOk = 0;
        for (ShipmentDetail shipmentDetail1 : shipmentDetailList) {
            if (shipmentDetail1.getIsDelete() == 0) {
                isOk = 1;
                break;
            }
        }
        if (isOk == 1) return;
        Wrapper<Shipment> shipmentWrapper = new EntityWrapper<>();
        shipmentWrapper.eq("id", oldDetail.getShipmentId());
        Shipment shipment = new Shipment();
        shipment.setIsDelete(1);
        shipmentService.update(shipment, shipmentWrapper);

        //deletePricePurchase(shipmentOrderDTO, authorization, shipTask, shipment, orderItem);
    }

    /**
     * 删除价格
     */
    public void deletePricePurchase(String authorization,
                                     ShipTask shipTask,
                                     Shipment shipment,
                                     ShipOrderItem shipOrderItem) {
        //四大家 判断
        //LOGGER.info("连接BMS 删除支付价格--->param:{}", JSON.toJSONString(shipmentOrderDTO));
        if (FourPeopleEnum.JST.getId().equals(shipment.getLspId())
                || FourPeopleEnum.JX.getId().equals(shipment.getLspId())
                || FourPeopleEnum.LYTD.getId().equals(shipment.getLspId())
                || FourPeopleEnum.YJ.getId().equals(shipment.getLspId())) {
            PricePurchaseDTO pricePurchaseDTO = new PricePurchaseDTO();
            pricePurchaseDTO.setShipmentCode(shipment.getCode());
            pricePurchaseDTO.setShipTaskCode(shipTask == null ? null : shipTask.getCode());
            pricePurchaseDTO.setShipOrderItemId(shipOrderItem == null ? null : shipOrderItem.getId());
            pricePurchaseDTO.setCreateFrom(TableStatusEnum.STATUS_10.getCode());
            List<NameValuePair> headNamePairs = Lists.newArrayList();
            headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
            TmsExplogLine explogLine = new TmsExplogLine();
            explogLine.setExportType("BS_CANCEL");
            explogLine.setExportKey(shipment.getShipSourceKey());
            explogLine.setTargetSys("BMS");
            explogLine.setInterfaceUrl(deletePurchaseUrl);
            explogLine.setDataContent(JSON.toJSONString(pricePurchaseDTO));
            explogLine.setGmtCreate(new Date());
            explogLine.setRemarks("取消发运推送BMS");
            try {
                LOGGER.info("连接BMS 删除支付单据url:{},param:{}", deletePurchaseUrl, JSON.toJSONString(pricePurchaseDTO));
                String strResult = HttpClientUtil.postJson(deletePurchaseUrl, headNamePairs,
                        JSON.toJSONString(pricePurchaseDTO), socketTimeout);
                LOGGER.info("连接BMS 删除支付单据 result:{}", strResult);
                explogLine.setExportStatus(TableStatusEnum.STATUS_Y.getCode());
                explogLine.setExportResponse(strResult);
            } catch (Exception e) {
                LOGGER.error("连接BMS 删除支付单据 error: {}", e);
                explogLine.setExportStatus(TableStatusEnum.STATUS_N.getCode());
            }
            explogLineService.insert(explogLine);
        }
    }

    /**
     * 添加支付价格表
     */
    private void insertPricePurchaseIU(ShipmentOrderDTO shipmentOrderDTO,
                                       String shipmentCode, String shipTaskCode,
                                       ShipOrderItem shipOrderItem,
                                       CarrierInfoLineVO carrierInfoLineVO,
                                       List<LocationVo> omsLocations,
                                       String authorization) {
        //四大家 判断
        LOGGER.info("连接BMS 获取支付暂估价--->param:{}", JSON.toJSONString(shipmentOrderDTO));
        if (FourPeopleEnum.JST.getId().equals(shipmentOrderDTO.getServiceProviderId())
                || FourPeopleEnum.JX.getId().equals(shipmentOrderDTO.getServiceProviderId())
                || FourPeopleEnum.LYTD.getId().equals(shipmentOrderDTO.getServiceProviderId())
                || FourPeopleEnum.YJ.getId().equals(shipmentOrderDTO.getServiceProviderId())) {
            PricePurchaseDTO pricePurchaseDTO = new PricePurchaseDTO();
            pricePurchaseDTO.setShipmentCode(shipmentCode);
            pricePurchaseDTO.setShipTaskCode(shipTaskCode);
            pricePurchaseDTO.setItemUid(shipOrderItem.getIssueItemId());
            pricePurchaseDTO.setShipOrderItemId(shipOrderItem.getId());
            pricePurchaseDTO.setLspId(carrierInfoLineVO.getLspId());
            pricePurchaseDTO.setLspName(carrierInfoLineVO.getLspName());
            pricePurchaseDTO.setDriverId(carrierInfoLineVO.getDriverId());
            pricePurchaseDTO.setDriverName(carrierInfoLineVO.getDriverName());
            pricePurchaseDTO.setCreateFrom(TableStatusEnum.STATUS_10.getCode());//10-OTM，20-人送，30-其他
            pricePurchaseDTO.setTransTypeId(StringUtils.isEmpty(shipmentOrderDTO.getTransportModeId()) ? 0L : Long.valueOf(shipmentOrderDTO.getTransportModeId()));
            if (Objects.nonNull(carrierInfoLineVO.getId()))
                pricePurchaseDTO.setCarrierId(carrierInfoLineVO.getId());
            pricePurchaseDTO.setCarrierPlate(shipmentOrderDTO.getPlateNo());
            if (!StringUtils.isEmpty(carrierInfoLineVO.getFleetId())) {
                pricePurchaseDTO.setFleetId(carrierInfoLineVO.getFleetId());
                pricePurchaseDTO.setFleetName(carrierInfoLineVO.getFleetName());
            }

            for (LocationVo location : omsLocations) {
                if (TableStatusEnum.STATUS_2.getCode().equals(String.valueOf(location.getTypeId()))) {
                    pricePurchaseDTO.setDepartLocationAdCode(location.getAdCode());
                    pricePurchaseDTO.setDepartAdressName(location.getValue());
                    pricePurchaseDTO.setDepartLocationId(location.getId());
                }
                if (TableStatusEnum.STATUS_4.getCode().equals(String.valueOf(location.getTypeId()))) {
                    pricePurchaseDTO.setDestLocationId(location.getId());
                    pricePurchaseDTO.setDestAdderssName(location.getValue());
                    pricePurchaseDTO.setDestLocationAdCode(location.getAdCode());
                }

            }

            Map<String, BigDecimal> stringBigDecimalMap = priceAndMiles(shipOrderItem.getItemSourceKey(), authorization);
            if (stringBigDecimalMap != null) {
                pricePurchaseDTO.setExtPurchasePrice(stringBigDecimalMap.get("price"));
                pricePurchaseDTO.setMileage(stringBigDecimalMap.get("miles"));
            }
            //pricePurchaseDTO.setCreator(Long.valueOf(AccountUtil.getAccountInfoFromSecurityContext().getAccountId()));
            pricePurchaseDTO.setTenantId(shipmentOrderDTO.getTenantId());
            List<NameValuePair> headNamePairs = Lists.newArrayList();
            headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
            String strReturn = null;
            try {
                LOGGER.info("连接BMS 生成支付单据url:{},param:{}", importPurchaseUrl, JSON.toJSONString(pricePurchaseDTO));
                strReturn = HttpClientUtil.postJson(importPurchaseUrl, headNamePairs,
                        JSON.toJSONString(pricePurchaseDTO), socketTimeout);
                LOGGER.info("连接BMS 生成支付单据result:{}", strReturn);
                if (StringUtils.isEmpty(strReturn)) {
                    interfaceCompensationService.interfaceCompensationData(JSON.toJSONString(pricePurchaseDTO), "返回为空", FailureDataType.PURCHASE.getId(), authorization);
                }
            } catch (Exception e) {
                interfaceCompensationService.interfaceCompensationData(JSON.toJSONString(pricePurchaseDTO), "连接超时", FailureDataType.INCOME.getId(), authorization);
                LOGGER.error("insertPricePurchaseIU error: {}", e);
            }
        }
    }

    /**
     * 更新支付价格表
     */
    private void UpdatePricePurchase(String shipOrderCode,
                                     ShipmentOrderDTO shipmentOrderDTO,
                                     String authorization,
                                     ShipOrderItem orderItem) {
        if (FourPeopleEnum.JST.getId().equals(shipmentOrderDTO.getServiceProviderId())
                || FourPeopleEnum.JX.getId().equals(shipmentOrderDTO.getServiceProviderId())
                || FourPeopleEnum.LYTD.getId().equals(shipmentOrderDTO.getServiceProviderId())
                || FourPeopleEnum.YJ.getId().equals(shipmentOrderDTO.getServiceProviderId())) {
            Wrapper<ShipTask> shipTaskWrapper = new EntityWrapper<>();
            shipTaskWrapper.eq("ship_order_code", shipOrderCode);
            ShipTask shipTask = shipTaskService.selectOne(shipTaskWrapper);
            PricePurchaseDTO pricePurchaseDTO = new PricePurchaseDTO();
            pricePurchaseDTO.setShipTaskCode(shipTask.getCode());
            pricePurchaseDTO.setItemUid(orderItem.getIssueItemId());
            pricePurchaseDTO.setIsDelete(Integer.valueOf(TableStatusEnum.STATUS_1.getCode()));
            List<NameValuePair> headNamePairs = Lists.newArrayList();
            headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
            String strReturn = HttpClientUtil.postJson(updateOrInsertPurchaseUrl, headNamePairs,
                    JSON.toJSONString(pricePurchaseDTO), socketTimeout);
            LOGGER.info("UpdatePricePurchase result {}", strReturn);
        }
    }

    /**
     * 获取价格跟里程
     */
    private Map<String, BigDecimal> priceAndMiles(String orderNo, String authorization) {
        Map<String, BigDecimal> result = new HashMap<>();
        Map<String, String> orderno = new HashMap<>();
        orderno.put("orderno", orderNo);
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
        String priceAndMiles = HttpClientUtil.postJson(integrationUrl + getPriceAndMilesUrl, headNamePairs,
                JSON.toJSONString(orderno), socketTimeout);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(priceAndMiles)) {
            JSONObject jsonObject = JSONObject.parseObject(priceAndMiles);
            if (jsonObject.getIntValue("code") == 0) {
                JSONObject data = jsonObject.getJSONObject("data");
                if (data != null) {
                    //暂估价
                    result.put("price", data.getBigDecimal("price"));
                    //计价里程
                    result.put("miles", data.getBigDecimal("miles"));
                }
            } else {
                LOGGER.error("获取价格里程失败" + jsonObject.getString("message"));
//                throw new BaseException("连接OTM获取价格里程失败");
            }
        } else {
            LOGGER.error("连接OTM获取价格里程失败");
//            throw new BaseException("连接OTM获取价格里程失败");
        }

        return result;
    }

    /**
     * 获取运输方式id
     */
    private Long getServiceTypeId(String serviceTypeName) {
        List<ServiceTypeVO> allServiceTypeList = mdmUtil.getAllServiceTypeList();
        for (ServiceTypeVO serviceTypeVO : allServiceTypeList) {
            if (serviceTypeVO.getValue().equals(serviceTypeName)) {
                return serviceTypeVO.getId();
            }
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> queryShipOrderItemCount(List<Map<String, Object>> shipSourceKeys) {
        if(null == shipSourceKeys || shipSourceKeys.isEmpty()){
            return null;
        }

        shipSourceKeys.forEach(shipSource ->{
            Integer countQty = baseMapper.selectShipOrderItemCount((String)shipSource.get("shipmwnt_xid"));
            shipSource.put("vehicleQty",countQty);
        });

        return shipSourceKeys;
    }

}
